package com.csu.common.handler;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.log4j.Logger;

/**
 * @项目名称：cloud_market
 * @类名称：SQLInterceptor
 * @类描述：拦截打印出调试的sql语句
 * @创建人：TangC
 * @创建时间：2015-6-19 上午9:13:40
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class SQLInterceptor implements Interceptor
{
    private static final Logger LOGGER = Logger.getLogger(SQLInterceptor.class);

    // 这个是真正的拦截
    public Object intercept(Invocation invocation) throws Throwable
    {
        RoutingStatementHandler statement = (RoutingStatementHandler) invocation.getTarget();

        BoundSql boundSql = statement.getBoundSql();

        String sql = boundSql.getSql();

        sql = sql.replaceAll("(\n)+", " ").replaceAll("(\t)+", " ").replaceAll("( )+", " ");

        LOGGER.debug("sql:" + sql);

        return invocation.proceed();
    }

    public Object plugin(Object target)
    {
        return Plugin.wrap(target, this);
    }

    // 这里可以获取配置文件配置的show_sql值
    public void setProperties(Properties arg0)
    {

    }
}